package com.dhj.yygh.api;

import com.dhj.yygh.common.exception.YyghException;
import com.dhj.yygh.common.helper.JwtHelper;
import com.dhj.yygh.common.result.MyResult;
import com.dhj.yygh.common.utils.AuthContextHolder;
import com.dhj.yygh.model.user.UserInfo;
import com.dhj.yygh.service.UserInfoService;
import com.dhj.yygh.vo.user.LoginVo;
import com.dhj.yygh.vo.user.UserAuthVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Api(tags = "用户相关 api")
@RestController
@RequestMapping("/api/user")
public class UserInfoApiController {

    @Autowired
    UserInfoService userInfoService;

    @ApiOperation("用户手机号登录接口")
    @PostMapping("/login")
    public MyResult<Map<String, Object>> login(
            @RequestBody LoginVo loginVo) {

        // 登陆后返回一些用户信息，如用户名，进行回显
        Map<String, Object> resultMap;
        try {
            resultMap = userInfoService.loginUser(loginVo);
            return MyResult.ok(resultMap);
        } catch (YyghException e) {
            resultMap = new HashMap<>();
            resultMap.put("code", e.getCode());
            resultMap.put("message", e.getMessage());
            return MyResult.fail(resultMap);
        }
    }

    @ApiOperation("用户认证接口")
    @PostMapping("/auth/userAuth")
    public MyResult userAuth(
            @RequestBody UserAuthVo userAuthVo,
            HttpServletRequest req) {

        // 用户认证
        userInfoService.userAuth(userAuthVo, AuthContextHolder.getUserId(req));
        return MyResult.ok();

    }

    @ApiOperation("根据用户 id 获取用信息")
    @GetMapping("/getUserInfoById")
    public MyResult<UserInfo> getUserInfo(HttpServletRequest req) {

        Long userId = AuthContextHolder.getUserId(req);

        UserInfo userInfo = userInfoService.getById(userId);

        return MyResult.ok(userInfo);
    }
}
